package com.example.treehole;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DividerItemDecoration;

import com.example.treehole.base.BaseBindingActivity;
import com.example.treehole.base.BindAdapter;
import com.example.treehole.bean.CollectStatus;
import com.example.treehole.bean.Post;
import com.example.treehole.bean.PostComment;
import com.example.treehole.bean.User;
import com.example.treehole.databinding.ActivityPostDeatilBinding;
import com.example.treehole.databinding.ItemCommentTextBinding;
import com.example.treehole.util.Api;
import com.example.treehole.util.BlueTextUtil;
import com.example.treehole.util.HttpUtil;
import com.example.treehole.util.SomeUtil;

import java.util.HashMap;
import java.util.List;

/**
 * 帖子详情界面
 */
public class PostDetailActivity extends BaseBindingActivity<ActivityPostDeatilBinding> {


    private BindAdapter<ItemCommentTextBinding, PostComment> adapter = new BindAdapter<ItemCommentTextBinding, PostComment>() {
        @Override
        public ItemCommentTextBinding createHolder(ViewGroup parent) {
            return ItemCommentTextBinding.inflate(getLayoutInflater(), parent, false);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void bind(ItemCommentTextBinding item, PostComment postComment, int position) {
            item.tvUpName.setText(postComment.nickname + (postComment.userid.equals(App.user.id) ? "（我的评论）" : ""));
            item.tvUpTime.setText(postComment.time);
            if (postComment.toUser != null) {
                BlueTextUtil.setBlueText(item.text, "回复:" + postComment.toUser.nickname, "回复 " + postComment.toUser.nickname + " :" + postComment.content, v -> {
                    if (postComment.anonymous) {
                        return;
                    }
                    HashMap<String, Object> params = new HashMap<>();
                    params.put("userid", postComment.toId);
                    HttpUtil.getModel(Api.GET_USER_BY_ID, params, User.class, new HttpUtil.OnNetModelListener<User>() {
                        @Override
                        public void success(User data, String message) {
                            Intent intent = new Intent(PostDetailActivity.this, UserPageActivity.class);
                            intent.putExtra("user", data);
                            startActivity(intent);
                        }

                        @Override
                        public void error(String message) {

                        }
                    });
                });
            } else {
                item.text.setText(postComment.content);
            }

            loadImage(postComment.face, item.ivFace);
            item.getRoot().setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (postComment.userid.equals(App.user.id)) {
                        new AlertDialog.Builder(PostDetailActivity.this).setMessage("确定要删除评论吗")
                                .setPositiveButton("取消", null).setNegativeButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        doDelete(postComment);
                                    }
                                }).show();
                    }
                    return true;
                }
            });
            item.getRoot().setOnClickListener(v -> {
                if (postComment.anonymous) {
                    return;
                }
                toPostComment = postComment;
                viewBinder.commentEdit.setHint("回复" + toPostComment.nickname);
            });
        }
    };

    private void refreshCollect() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("type", "帖子");
        params.put("targetId", post.id);
        params.put("userid", App.user.id);
        HttpUtil.getModel(Api.COLLECT_GET_STATUS, params, CollectStatus.class, new HttpUtil.OnNetModelListener<CollectStatus>() {
            @SuppressLint("SetTextI18n")
            @Override
            public void success(CollectStatus data, String message) {
                if (data.currentStatus) {
                    viewBinder.tvCollect.setText("取消收藏");
                } else {
                    viewBinder.tvCollect.setText("收藏");
                }
            }

            @Override
            public void error(String message) {

            }
        });
    }

    private void refreshLike() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("type", "帖子");
        params.put("targetId", post.id);
        params.put("userid", App.user.id);
        HttpUtil.getModel(Api.LIKE_GET_STATUS, params, CollectStatus.class, new HttpUtil.OnNetModelListener<CollectStatus>() {
            @SuppressLint("SetTextI18n")
            @Override
            public void success(CollectStatus data, String message) {
                if (data.currentStatus) {
                    viewBinder.tvLike.setText("取消点赞");
                } else {
                    viewBinder.tvLike.setText("点赞");
                }
            }

            @Override
            public void error(String message) {

            }
        });
    }

    private void doDelete(PostComment postComment) {
        showLoading();
        HashMap<String, Object> params = new HashMap<>();
        params.put("id", postComment.id);
        HttpUtil.delete(Api.DELETE_POST_COMMENT, params, new HttpUtil.OnNetStringListener() {
            @Override
            public void success(String data, String message) {

                adapter.getData().remove(postComment);
                adapter.notifyDataSetChanged();
                display$Toast(message);
            }

            @Override
            public void error(String message) {
                display$Toast(message);
            }
        });
    }

    private PostComment toPostComment;

    @Override
    protected void initListener() {

        viewBinder.sendBtn.setOnClickListener(view -> {
            String content = viewBinder.commentEdit.getText().toString().trim();
            if (content.isEmpty()) {
                toast("最好还是写点什么再发...");
                return;
            }
            PostComment postComment = new PostComment();
            postComment.userid = App.user.id;
            postComment.content = content;
            postComment.anonymous = viewBinder.cbAnonymous.isChecked();
            postComment.nickname = App.user.nickname;
            postComment.postId = post.id;
            postComment.face = App.user.face;
            postComment.toId = toPostComment == null ? null + "" : toPostComment.userid;
            postComment.time = SomeUtil.getTime();
            viewBinder.commentEdit.setText("");
            setComment(postComment);
        });
    }

    private void setComment(PostComment postComment) {
        showLoading();
        HttpUtil.post(Api.SEND_COMMENT, HttpUtil.toJSON(postComment), new HttpUtil.OnNetStringListener() {
            @Override
            public void success(String data, String message) {
                dismissLoading();
                refreshComment();
                toast(message);
            }

            @Override
            public void error(String error) {
                dismissLoading();
                toast(error);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    private Post post;

    @SuppressLint("SetTextI18n")
    @Override
    protected void initData() {
        post = (Post) getIntent().getSerializableExtra("post");

        viewBinder.tvUpTime.setText(post.time);
        viewBinder.content.setText(post.content);
        viewBinder.tvUpName.setText(post.nickname);
        loadImage(post.face, viewBinder.ivFace);
        viewBinder.title.setText(post.title);
        refreshComment();
        if (!post.file.isEmpty()) {
            viewBinder.ivImage.setVisibility(View.VISIBLE);
            loadImage(post.file, viewBinder.ivImage);
        } else {
            viewBinder.ivImage.setVisibility(View.GONE);
        }
        viewBinder.ivFace.setOnClickListener(v -> {
            if (post.anonymous) {
                return;
            }
            HashMap<String, Object> params = new HashMap<>();
            params.put("userid", post.userid);
            HttpUtil.getModel(Api.GET_USER_BY_ID, params, User.class, new HttpUtil.OnNetModelListener<User>() {
                @Override
                public void success(User data, String message) {
                    Intent intent = new Intent(PostDetailActivity.this, UserPageActivity.class);
                    intent.putExtra("user", data);
                    startActivity(intent);
                }

                @Override
                public void error(String message) {

                }
            });
        });
        viewBinder.tvCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<String, Object> params = new HashMap<>();
                params.put("type", "帖子");
                params.put("targetId", post.id);
                params.put("userid", App.user.id);
                HttpUtil.postModel(Api.COLLECT_ADD, params, CollectStatus.class, new HttpUtil.OnNetModelListener<CollectStatus>() {
                    @Override
                    public void success(CollectStatus data, String message) {
                        if (data.currentStatus) {
                            viewBinder.tvCollect.setText("取消收藏");
                        } else {
                            viewBinder.tvCollect.setText("收藏");
                        }
                    }

                    @Override
                    public void error(String message) {

                    }
                });
            }
        });

        viewBinder.tvLike.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<String, Object> params = new HashMap<>();
                params.put("type", "帖子");
                params.put("targetId", post.id);
                params.put("userid", App.user.id);
                HttpUtil.postModel(Api.LIKE_ADD, params, CollectStatus.class, new HttpUtil.OnNetModelListener<CollectStatus>() {
                    @Override
                    public void success(CollectStatus data, String message) {
                        if (data.currentStatus) {
                            viewBinder.tvLike.setText("取消点赞");
                        } else {
                            viewBinder.tvLike.setText("点赞");
                        }
                    }

                    @Override
                    public void error(String message) {

                    }
                });
            }
        });
        viewBinder.commentRecycler.addItemDecoration(new DividerItemDecoration(this, LinearLayout.VERTICAL));
        viewBinder.commentRecycler.setAdapter(adapter);
        refreshCollect();
        refreshLike();
    }


    private void refreshComment() {
        showLoading();
        HashMap<String, Object> params = new HashMap<>();
        params.put("postId", post.id);
        HttpUtil.getList(Api.GET_COMMENT_BY_ID, params, PostComment.class, new HttpUtil.OnNetListListener<PostComment>() {
            @Override
            public void success(List<PostComment> data, String message) {
                toast("评论获取成功");
                dismissLoading();
                adapter.getData().clear();
                adapter.getData().addAll(data);
                adapter.notifyDataSetChanged();
            }

            @Override
            public void error(String error) {
                toast(error);
                dismissLoading();
            }
        });
    }

}